<template>
  <div class="send-medici-container">
    <!-- 顶部区域 -->
    <div class="send-medici-header">
		<i class="el-icon-xy" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #00aa00;color: #fff;"></i>
		<h4 style="margin-left: 12px;">西药房门诊发药</h4>
    </div>
    
    <!-- 主体区域 -->
    <div class="send-medici-main">
      <!-- 左侧区域 (30%宽度) -->
      <div class="send-medici-left">
        <!-- 左侧上部表单 -->
        <div class="left-form">
          <el-form label-position="left" size="small">
            <el-form-item label="药房名称">
              <el-select v-model="form.pharmacyName" placeholder="请选择药房">
                <el-option label="西药房" value="西药房"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="发药窗口">
              <el-select v-model="form.dispensingWindow" placeholder="请选择窗口">
                <el-option label="门诊1号窗口" value="门诊1号窗口"></el-option>
                <el-option label="门诊2号窗口" value="门诊2号窗口"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="窗口状态">
              <el-radio-group v-model="form.windowStatus">
                <el-radio label="启用">启用</el-radio>
                <el-radio label="暂停使用">暂停使用</el-radio>
              </el-radio-group>
            </el-form-item>
                  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">健康ID</span>
				  <el-input v-model="form.healthId" placeholder="请输入健康ID"></el-input>
				</div>
			  </el-form-item>
			  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">处方查找</span>
				  <el-input v-model="form.prescriptionSearch" placeholder="处方编号"></el-input>
				</div>
			  </el-form-item>
			  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">患者姓名</span>
					<el-input v-model="form.name" placeholder="姓名/拼音简码"></el-input>
					<el-button type="primary" size="small" style="margin-left: 10px;" :loading="loading" @click="getUserInfo">刷新</el-button>
				</div>
			  </el-form-item>
			  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">刷新时长</span>
				  <el-input v-model="form.refreshTime" placeholder="秒" style="width: 60px;"></el-input>
				  <el-checkbox v-model="form.showBatch" style="margin-left: 10px;">显示药品批次</el-checkbox>
				</div>
			  </el-form-item>
			</el-form>
        </div>
        
        <!-- 左侧下部表格 -->
        <div class="left-table">
          <el-table
            :data="leftTableData"
            border
            style="width: 100%"
            :height="leftTableHeight"
			@row-dblclick="getDataValue"
            size="small">
            <el-table-column type="index" label="行号" width="48"></el-table-column>
            <el-table-column prop="name" label="病人姓名" width="88"></el-table-column>
            <el-table-column prop="age" label="年龄" width="60"></el-table-column>
			<el-table-column prop="sex" sortable label="性别" width="80">
			  <template slot-scope="scope">
			    <span>
			      <i :class="scope.row.sex === 1? 'el-icon-male' : 'el-icon-female'" 
			          :style="{color: scope.row.sex === 1 ? '#409EFF' : '#F56C6C'}"></i>
			      {{ scope.row.sex === 1 ? '男' : '女' }}
			    </span>
			  </template>
			</el-table-column>
			<el-table-column prop="patientId" label="健康id" width="80"></el-table-column>
			<el-table-column prop="cardId" label="身份证号码" width="188"></el-table-column>
			<el-table-column prop="fullName" label="处方医生" width="100"></el-table-column>
			<el-table-column prop="state" label="状态">
				<template slot-scope="{ row }">
					<!-- 根据state显示不同的图标 -->
					<div class="stateValue" style="border-radius: 4px;background-color: #e2fff6;text-align: center;color: #004a00;">
						<i :class="statusIconMap[row.state]" :style="{ color: statusColorMap[row.state] }"></i>
						<span>{{ statusMap[row.state] || '未知状态' }}</span>
					</div>
				</template>
			</el-table-column>
<!--        <el-table-column prop="rxName" label="处方类型" width="100"></el-table-column>
            <el-table-column prop="rxNo" label="处方编号" width="120"></el-table-column>
			<el-table-column prop="saleAmt" label="处方金额" width="80"></el-table-column>
			<el-table-column prop="deptName" label="处方科室" width="120"></el-table-column>
			<el-table-column prop="fullName" label="处方医生" width="120"></el-table-column> -->
			
            <el-table-column prop="remark" label="备注" width="80"></el-table-column>
          </el-table>
        </div>
      </div>
      
      <!-- 右侧区域 (70%宽度) -->
      <div class="send-medici-right">
        <!-- 右侧上部表单 -->
        <div class="right-form">
          <el-form :inline="true" size="small">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="处方编号">
                  <el-input v-model="rightForm.rxNo" placeholder="请输入处方编号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病员姓名">
                  <el-input v-model="rightForm.name" placeholder="请输入病员姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病人身份证">
                  <el-input v-model="rightForm.cardId" placeholder="请输入病人身份证"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="性别">
					<el-select v-model="rightForm.sex" placeholder="请选择性别">
					  <el-option v-for="item in sexOptions" :key="item.id" :label="item.label" :value="item.id">
					  <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
					</el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="年龄">
                  <el-input v-model="rightForm.age" placeholder="请输入年龄"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="健康id">
                  <el-input v-model="rightForm.patientId" placeholder="健康id"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处方科室">
                  <el-input v-model="rightForm.deptName" placeholder="请输入处方科室"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处方医生">
                  <el-input v-model="rightForm.fullName" placeholder="请输入处方医生"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="处方金额">
                  <el-input v-model="rightForm.saleAmt" placeholder="请输入处方金额"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处方类型">
                  <el-input v-model="rightForm.rxName" placeholder="请输入处方类型"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="皮试处方">
                  <el-select v-model="rightForm.sex" placeholder="皮试处方">
                    <el-option v-for="item in YNOption" :key="item.id" :label="item.label" :value="item.id">
                    <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="代办人姓名">
                  <el-input v-model="rightForm.agnterName" placeholder="请输入代办人姓名"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="代办人身份证">
                  <el-input v-model="rightForm.agnterCretno" placeholder="请输入代办人身份证"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="西医诊断">
                  <el-input v-model="rightForm.icdName" placeholder="请输入西医诊断"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-input :value="rightForm.state === 1 ? '启用' : '禁用'" placeholder="请输入症状及体征" readonly></el-input>
                </el-form-item>
				
              </el-col>
              <el-col :span="6">
                <el-form-item label="药房">
                  <el-input v-model="rightForm.pharmacyName" placeholder="请输入药房信息"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="其它信息">
                  <el-input v-model="rightForm.otherInfo" placeholder="请输入其它信息"></el-input>
                </el-form-item>
              </el-col>
<!--              <el-col :span="6">
                <el-form-item label="配药人">
                  <el-input v-model="rightForm.dispenser" placeholder="请输入配药人"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="配药窗口">
                  <el-input v-model="rightForm.dispensingWindow" placeholder="请输入配药窗口"></el-input>
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="备注">
                  <el-input v-model="rightForm.remark" placeholder="请输入备注"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

          <!-- 右侧下部表格 -->
            <div class="right-table">
              <el-table
                ref="rightTable"
                :data="rightTableData"
                border
                style="width: 100%"
                :height="rightTableHeight"
                size="small"
                show-summary
                :summary-method="getSummaries">
                <el-table-column type="index" label="行号" width="60"></el-table-column>
                <el-table-column prop="drugName" label="药品名称" width="150"></el-table-column>
                <el-table-column prop="drugSpec" label="药品规格" width="120"></el-table-column>
				<el-table-column prop="pacSpec" label="包装规格" width="120"></el-table-column>
                <el-table-column prop="dosform" label="剂型" width="100"></el-table-column>
                <el-table-column prop="cnt" label="数量" width="80"></el-table-column>
                <el-table-column prop="unt" label="单位" width="60"></el-table-column>
                <el-table-column prop="usageName" label="用法" width="120"></el-table-column>
                <el-table-column prop="frequency" label="频次" width="100"></el-table-column>
                <el-table-column prop="prdDays" label="天数" width="60"></el-table-column>
                <el-table-column prop="purcPric" label="单价" width="80"></el-table-column>
                <el-table-column prop="saleAmt" label="金额" width="80"></el-table-column>
                <el-table-column prop="manuLotnum" label="批号" width="100"></el-table-column>
                <el-table-column prop="expyDate" label="有效期" width="120"></el-table-column>
                <el-table-column prop="prodentpName" label="生产厂家" width="150"></el-table-column>
              </el-table>
            </div>
 
      </div>
    </div>
    
    <!-- 底部区域 (100%宽度) -->
    <!-- 底部按钮区域 -->
    <div class="send-medici-bottom">
      <div class="bottom-left">
        <el-button :loading="buttonLoading.print" type="warning" size="small">打印</el-button>
        <el-checkbox :disabled="buttonLoading.print" v-model="closeAfterPrint" style="margin-left: 10px;">自动打印</el-checkbox>
      </div>
      <div class="bottom-right">
        <el-button :loading="buttonLoading.callPatient" type="primary" size="small">呼叫患者</el-button>
        <el-button :loading="buttonLoading.skipNumber" type="primary" size="small">一键过号</el-button>
        <el-button :loading="buttonLoading.refund" type="primary" size="small">许可退费</el-button>
        <el-button :loading="buttonLoading.printPrescription" type="primary" size="small">打印处方</el-button>
        <el-button :loading="buttonLoading.batchDispense" type="primary" size="small">批量发药</el-button>
        <el-button :loading="buttonLoading.sendMedic" type="success" size="small" @click="sendMedic">发药</el-button>
        <el-button :loading="buttonLoading.close" type="danger" size="small">关闭</el-button>
      </div>
    </div>
	
	<!-- 完成发药对话框 -->
	  <el-dialog
	    :visible.sync="sendMedicineDialogVisible"
	    title="完成发药"
	    width="500px"
	    :before-close="handleSendMedicineClose"
	    class="send-medicine-dialog"
	  >
	    <div class="send-medicine-content">
	      <div class="info-item">
	        <span class="label">患者</span>
	        <span class="value">{{ sendMedicineData.patientName || '匿名患者' }}</span>
	      </div>
	      <div class="info-item">
	        <span class="label">诊断</span>
	        <span class="value">{{ sendMedicineData.diagnosis || '无诊断信息' }}</span>
	      </div>
	      <div class="info-item">
			  <span class="label">发药内容</span>
			  <div class="medicine-content">
				<el-link 
				  type="primary" 
				  @click="openTraceCodeDialog"
				  class="trace-code-link"
				>
				  追溯码（{{ sendMedicineData.traceCodeCount || 0 }}）
				</el-link>
				<div class="medicine-type" @click="toggleMedicineList">
				  <span>中西成药（{{ sendMedicineData.medicineCount || 0 }}种）</span>
				  <i :class="showMedicineList ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" style="margin-left: 8px;"></i>
				</div>
				
				<!-- 药品列表部分 -->
				<div 
				  class="medicine-list" 
				  :class="{ 'expanded': showMedicineList }"
				  :style="{ 'max-height': showMedicineList ? medicineListMaxHeight : '0' }"
				>
				  <div 
				    class="medicine-item" 
				    v-for="(item, index) in westernMedicines" 
				    :key="index"
				  >
				    <!-- 完成发药对话框中的药品列表样式修改 -->

				      <span class="medicine-name" :style="{ 
				        color: item.drugTracB === 1 ? 
				          (item.traceCodeCollected ? '#67C23A' : '#F56C6C') 
				          : 'inherit' 
				      }">
				        {{ item.drugName }}
				      </span>
				    }
				    <el-tag type="info" size="mini" style="margin-left: 8px;">西药</el-tag>
				    <span v-if="item.drugTracB === 1" style="margin-left: 10px;">
				      <span v-if="item.traceCodeCollected" style="color: #67C23A">
				        已录入追溯码 ({{ item.drgTracCnt }}个)
				      </span>
				      <span v-else style="color: #F56C6C">
				        该药品已强制要求追溯码，请先录入再进行发药！
				      </span>
				    </span>
				  </div>
				</div>
			  </div>
			</div>
		  </div>
	    
	    <div class="dialog-footer">
	      <el-checkbox v-model="sendMedicineData.printTogether">同时打印</el-checkbox>
	      <div class="footer-buttons">
	        <el-button size="mini" @click="sendMedicineDialogVisible = false">取消</el-button>
	        <!-- 发药对话框的确定按钮 -->
	        <el-button 
	          size="mini" 
	          type="primary" 
	          @click="confirmSendMedicine"
	          :disabled="hasUncollectedMandatoryTrace"
	        >
	          确定
	        </el-button>
	      </div>
	    </div>
	  </el-dialog>
	
	  <!-- 追溯码采集对话框 -->
	    <el-dialog
	      :visible.sync="traceCodeDialogVisible"
	      title="追溯码采集"
	      width="800px"
	      :before-close="handleTraceCodeClose"
	      class="trace-code-dialog"
	    >
	      <div class="trace-code-content">
	        <!-- 重要提醒 -->
	        <div class="important-reminder">
	          <div class="reminder-header">
	            <i class="el-icon-warning"></i>
	            <span>依码支付重要提醒</span>
	          </div>
	          <div class="reminder-content">
	            <p>1.请根据实际情况调整"整""零"发药数量（如：某药10支/盒，发药2盒，其中整装1盒，另1盒是拆零凑成，则将"整"调整为1盒）。</p>
	            <p>2.如果无法修改"整装"数量，请退费重新收费，在医保结算窗口进行调整。</p>
	          </div>
	        </div>
	    
	        <!-- 扫描输入区域 -->
	        <div class="scan-input-area">
	          <el-input
	            v-model="traceCodeInput"
	            placeholder="扫描或输入追溯码"
	            clearable
	            class="trace-code-input"
				:disabled="true"
	          >
	            <template slot="append">
	              <el-button icon="el-icon-search" @click="openScanDialog">扫描</el-button>
	            </template>
	          </el-input>
	          <div class="input-tips">
	            <el-link type="primary">发药项目无追溯码？</el-link>
	            <el-link type="primary">如何判断拆零？</el-link>
	          </div>
	        </div>
	    
	        <!-- 发药项目表格 -->
	        <el-table
			:data="traceCodeTableData"
			border
			style="width: 100%; margin-top: 16px"
			class="trace-code-table"
			>
	          <el-table-column prop="medicineName" label="待发药项目" width="200">
	            <template slot-scope="scope">
	              {{ scope.row.medicineName }}
	            </template>
	          </el-table-column>
	          <el-table-column prop="productCode" label="生产厂家" width="188">
	            <template slot-scope="scope">
	              {{ scope.row.productCode }}
	            </template>
	          </el-table-column>
	          <el-table-column prop="sendStatus" label="发药" width="80">
	            <template slot-scope="scope">
	              <el-tag :type="scope.row.sendStatus === '已关联' ? 'success' : 'warning'">
	                {{ scope.row.sendStatus }}
	              </el-tag>
	            </template>
	          </el-table-column>
	          <el-table-column prop="sendCombo" label="发药组合" width="100">
	            <template slot-scope="scope">
	              {{ scope.row.sendCombo }}
	            </template>
	          </el-table-column>
	          <el-table-column prop="drgTracCnt" label="追溯码扫码数量" width="120">
	            <template slot-scope="scope">
	              {{ scope.row.drgTracCnt }}
	            </template>
	          </el-table-column>
	          <el-table-column prop="drgTracCode" label="追溯码" width="188">
	                <template slot-scope="scope">
	                  <!-- 显示已绑定的追溯码 -->
	                  <span v-if="scope.row.drgTracCode">{{ scope.row.drgTracCode }}</span>
	                  <span v-else class="no-trace-code">未对码药品无需采集</span>
	                </template>
	              </el-table-column>

	        </el-table>
	      </div>
	    
	      <div slot="footer" class="trace-code-footer">
	        <!-- 追溯码采集对话框的完成按钮 -->
	        <el-button 
	          type="primary" 
	          @click="completeTraceCode"
	          :disabled="!isTraceCodeComplete"
	        >
	          完成
	        </el-button>
	        <!-- <el-button @click="saveTemporary">暂存</el-button> -->
	        <el-button @click="traceCodeDialogVisible = false">取消</el-button>
	      </div>
	    </el-dialog>
	  
	  <!-- 追溯码扫码录入弹框 -->
	    <el-dialog
	      :visible.sync="scanDialogVisible"
	      title="追溯码扫码录入"
	      width="600px"
	      class="scan-dialog"
	      :close-on-click-modal="false"
	    >
	      <div class="scan-container">
	        <div class="scan-header">
	          <i class="el-icon-camera"></i>
	          <span>请扫描药品追溯码</span>
	        </div>
	        
	        <div class="scan-preview">
	          <div class="scan-frame">
	            <div class="scan-line"></div>
	          </div>
	        </div>
	        
	        <div class="scan-input-area">
	          <el-input
	            v-model="scanInput"
	            placeholder="手动输入追溯码"
	            clearable
	            @keyup.enter.native="handleScanInput"
	          >
	            <template slot="append">
	              <el-button 
	                type="primary" 
	                @click="handleScanInput"
	                :disabled="!scanInput"
	              >
	                确认
	              </el-button>
	            </template>
	          </el-input>
	        </div>
	        
	        <div class="scan-tips">
	          <p><i class="el-icon-info"></i> 请将药品追溯码对准扫描框中心</p>
	          <p><i class="el-icon-info"></i> 扫码后请核对药品信息</p>
	        </div>
	        
	        <!-- 新增：匹配药品信息表格 -->
	        <div class="matched-medicines" v-if="matchedMedicines.length > 0">
	          <el-table
	            :data="matchedMedicines"
	            border
	            style="width: 100%; margin-top: 16px"
	            max-height="200"
	          >
	            <el-table-column prop="drugName" label="药品名称" width="150"></el-table-column>
	            <el-table-column prop="drugSpec" label="规格" width="120"></el-table-column>
	            <el-table-column label="追溯标识码">
	              <template slot-scope="scope">
	                {{ traceCodePrefix }}
	              </template>
	            </el-table-column>
	            <el-table-column label="完整追溯码" width="188">
	              <template slot-scope="scope">
	                {{ scanInput }}
	              </template>
	            </el-table-column>
	          </el-table>

	        </div>
	      </div>
	      
	      <div slot="footer" class="scan-footer">
	          <!-- 修改确认绑定按钮 -->
	          <el-button
	            type="primary" 
	            size="small"
	            @click="confirmTraceCode"
	            :disabled="matchedMedicines.length === 0"
	          >
	            确认绑定
	          </el-button>
	          <el-button size="small" @click="scanDialogVisible = false">取消</el-button>
	        </div>
	  </el-dialog>
	  
  </div>
</template>

<script>
// 接口
import { selectPatientInfo,fySave } from "@/api/MedicenHouse/WesternGive.js";

export default {
  name: 'SendMedici',
  inject: ['reload'], // 无痕刷新
  
	// 计算属性
    computed: {
	// 正确检测未采集的强制追溯码药品
	hasUncollectedMandatoryTrace() {
	  const result = this.westernMedicines.some(item => 
		item.drugTracB === 1 && 
		(!item.traceCodeCollected || !item.drgTracCode || item.drgTracCode.trim() === '')
	  );
	  
	  console.log('hasUncollectedMandatoryTrace:', result);
	  console.log('Western Medicines:', this.westernMedicines);
	  
	  return result;
	},
      
      // 检查追溯码是否采集完成
      isTraceCodeComplete() {
        return this.traceCodeTableData.every(item => {
          // 只需要检查强制追溯码药品
          if (item.rawData && item.rawData.drugTracB === 1) {
            return !!item.drgTracCode && item.drgTracCode.trim() !== '';
          }
          return true; // 非强制追溯码药品直接通过
        });
      },
      
      medicineListMaxHeight() {
        if (!this.westernMedicines || this.westernMedicines.length === 0) return '0';
        
        const itemHeight = 40;
        const maxVisibleItems = 5;
        const calculatedHeight = Math.min(this.westernMedicines.length, maxVisibleItems) * itemHeight;
        
        return `${calculatedHeight}px`;
      }
    },
  
  data() {
    return {
		searchedValue:'', // 患者姓名
		patientId:'', // 健康ID
		rxNoValue:'', // 处方编码
		// 新增扫码对话框相关数据
		scanDialogVisible: false,
		scanInput: '',
		currentScanItem: null,
		// blean
		loading:false,
		sexOptions:[{id:1,label:'男',value:'男'},{id:2,label:'女',value:'女'}],
		YNOption:[{id:0,label:'否'},{id:1,label:'是'}],//库房
      form: {
        pharmacyName: '西药房',
        dispensingWindow: '1号窗口',
        windowStatus: '启用',
        healthId: '',
        prescriptionSearch: '',
        name: '',
        refreshTime: '10',
        showBatch: true
      },
	  // 发药对话框相关数据
	sendMedicineDialogVisible: false,
	sendMedicineData: {
	  patientName: '',
	  diagnosis: '',
	  traceCodeCount: 0,
	  medicineCount: 0,
	  printTogether: false
	},
	
	// 追溯码对话框相关数据
	traceCodeDialogVisible: false,
	traceCodeInput: '',
	traceCodeTableData: [
	  {
		medicineName: '小柴胡汤丸 8g*9袋/盒',
		productCode: '朗致集团万荣',
		sendStatus: '未关联',
		sendCombo: '2盒',
		drgTracCnt: '2盒',
		drgTracCode: ''
	  }
	],
	  showMedicineList: false, // 是否显示药品列表
	  westernMedicines: [], // 西药列表
	  timer: null, // 计时器
	  // loading: false, // 加载状态
	  buttonLoading: { // 各按钮的加载状态
		print: false,
		callPatient: false,
		skipNumber: false,
		refund: false,
		printPrescription: false,
		batchDispense: false,
		sendMedic: false,
		close: false
	  },
      rightForm: {
			"age": 0,
			"agnterCretno": "",
			"agnterName": "",
			"cardId": "",
			"deptName": "",
			"fullName": "",
			"icdName": "",
			"id": 0,
			"name": "",
			"patientId": 0,
			"remark": "",
			"rxName": "",
			"rxNo": 0,
			"saleAmt": 0,
			"sex": 0,
			"skintstRx": 0,
			"state": 0,
			"voList": [
				{
					"cnt": 0,
					"dosform": "",
					"drugId": 0,
					"drgTracCnt":"",
					"drugName": "",
					"drgTracCode": "",
					"drugSpec": "",
					"dugPurcId": 0,
					"expyDate": "",
					"frequency": "",
					"manuLotnum": "",
					"maxPurcPric": 0,
					"maxSalePric": 0,
					"minPurcPric": 0,
					"minSalePric": 0,
					"pacCnt": 0,
					"prdDays": 0,
					"prodentpName": "",
					"prodentpNameId": 0,
					"purcAmt": 0,
					"purcPric": 0,
					"purcType": "",
					"rdDetailsId": 0,
					"rxId": 0,
					"saleAmt": 0,
					"salePric": 0,
					"saleUnt": 0,
					"supplyCandidateId": 0,
					"unt": "",
					"usageName": "",
					"drugTracB":0,
					"drugTracMaxCnt":'',
					"drugTracMaxId":'',
					"drugTracMinId":'',
				}
			]
      },
      leftTableData: [
        {
          rowNumber: 1,
          patientName: '张三',
          prescriptionNumber: 'P20230001',
          patientType: '门诊',
          age: 35,
          callCount: 2,
          callStatus: '已完成',
          printCount: 1
        },
        {
          rowNumber: 2,
          patientName: '李四',
          prescriptionNumber: 'P20230002',
          patientType: '住院',
          age: 42,
          callCount: 1,
          callStatus: '待处理',
          printCount: 0
        }
      ],
	  detailsVo: [],
      rightTableData: [],
	  // props
	  statusMap: {
	  	0: '草稿',
	  	1: '已收费',
	  	2: '已配药',
	  	3: '已发药',
	  	4: '已退药'
	  },
	  statusIconMap: {
	  	0: 'el-icon-document',
	  	1: 'el-icon-top-left',
	  	2: 'el-icon-check',
	  	3: 'el-icon-bottom-right',
	  	4: 'el-icon-document-checked',
	  },
	  statusColorMap: {
	  	0: '#909399',
	  	1: '#67C23A',
	  	2: '#409EFF',
	  	3: '#E6A23C',
	  	4: '#F56C6C',
	  },
	  // 新增数据项
	  traceCodePrefix: '', // 追溯码前7位
	  matchedMedicines: [], // 匹配到的药品列表
      closeAfterPrint: true,
      leftTableHeight: '100%',
      rightTableHeight: '100%'
    }
  },
  mounted() {
	this.loadData();
    this.calculateTableHeights();
    window.addEventListener('resize', this.calculateTableHeights);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeights);
  },
  methods: {
	async loadData(){
		this.loading = true;
		let res = await selectPatientInfo({
			name:this.searchedValue,
			patientId:this.patientId,
			rxNo:this.rxNoValue,
		});
		if(res.code === 200){
			this.leftTableData = res.data
			console.log(this.leftTableData,'leftTableDataleftTableData');
			this.totalSize = res.data.totalSize
			this.loading = false;
		}else{
			// this.$message({ type: 'error', message: res.message });
			this.tableData = [];
			this.loading = false;
		}
	  },
	  // 刷新按钮查询条件
	  getUserInfo(){
		this.searchedValue = this.form.name; // 患者姓名
		this.patientId = this.form.healthId; // 健康id
		this.rxNoValue = this.form.rxNoValue; // 处方查找
		this.loadData();
	  },

	// 双击事件
	getDataValue(row) {
	    console.log(row);
	    this.rightForm = row;
	
	    // 确保金额和数量是数字类型，并且确保有drugTracB属性
	    this.rightTableData = row.voList.map(item => ({
	      ...item,
	      drugTracB: item.drugTracB || 0, // 设置默认值
	      purcAmt: Number(item.purcAmt) || 0,
	      cnt: Number(item.cnt) || 0
	    }));
	
	    // 强制重新计算合计行
	    this.$nextTick(() => {
	      this.$refs.rightTable?.doLayout();
	    });
	},
		
	// 切换药品列表显示
	toggleMedicineList() {
	  this.showMedicineList = !this.showMedicineList;
	  
	  // 添加平滑展开/收起动画
	  this.$nextTick(() => {
		const listElement = this.$el.querySelector('.medicine-list');
		if (listElement) {
		  listElement.style.transition = 'max-height 0.3s ease';
		  listElement.style.overflow = 'hidden';
		  
		  if (this.showMedicineList) {
			listElement.style.maxHeight = '0';
			setTimeout(() => {
			  listElement.style.maxHeight = listElement.scrollHeight + 'px';
			}, 10);
		  } else {
			listElement.style.maxHeight = listElement.scrollHeight + 'px';
			setTimeout(() => {
			  listElement.style.maxHeight = '0';
			}, 10);
		  }
		}
	  });
	},

	  // 发药按钮点击事件
	  async sendMedic() {
	    // 检查是否有患者信息
	    if (!this.rightForm.patientId || !this.rightForm.name) {
	      this.$message.warning('暂未查询到患者诊断信息');
	      return;
	    }
	    
	    // 检查是否有强制追溯码的药品
	    const hasMandatoryTraceDrugs = this.rightTableData.some(item => item.drugTracB === 1);
	    
	    // 设置发药对话框数据时初始化药品列表
	    this.sendMedicineData = {
	      patientName: this.rightForm.name,
	      diagnosis: this.rightForm.icdName,
	      traceCodeCount: this.calculateTraceCodeCount(),
	      medicineCount: this.calculateMedicineCount(),
	      printTogether: false
	    };
	    
	    // 根据是否有强制追溯码药品决定是否展开
	    this.showMedicineList = hasMandatoryTraceDrugs;
	    
	    // 加载药品数据
	    this.loadWesternMedicines();
	    
	    // 显示发药对话框
	    this.sendMedicineDialogVisible = true;
	  },

	// 加载西药数据 - 添加默认值避免报错
	loadWesternMedicines() {
	  this.westernMedicines = this.rightTableData.map(item => ({
		...item,
		// 确保drugTracB有默认值
		drugTracB: item.drugTracB || 0,
		traceCodeCollected: false // 初始化为未采集状态
	  }));
	},
	
	// 计算已采集的追溯码数量
	calculateTraceCodeCount() {
	    return this.rightTableData.reduce((count, item) => {
	      // 只计算强制追溯码且已采集的药品
	      if (item.drugTracB === 1 && item.traceCodeCollected) {
	        return count + (item.drgTracCnt || 1);
	      }
	      return count;
	    }, 0);
	},
	
	// 计算药品数量
	calculateMedicineCount() {
	  // 根据实际业务逻辑计算
	  return this.rightTableData.length || 0;
	},
	
	// 打开追溯码采集对话框
	openTraceCodeDialog() {
	    this.traceCodeDialogVisible = true;
	    
	    // 转换药品数据为追溯码表格格式
	    this.traceCodeTableData = this.transformToTraceCodeData(this.westernMedicines);
	},
	
	// 打开扫码对话框
	openScanDialog(item) {
	  this.currentScanItem = item;
	  this.scanInput = '';
	  this.scanDialogVisible = true;
	  
	  // 自动聚焦输入框
	  this.$nextTick(() => {
		this.$refs.scanInput?.focus();
	  });
	},
	
	// 处理扫码输入
	handleScanInput() {
	    if (!this.scanInput || !this.currentScanItem) return;
	    
	    // 验证追溯码格式 (示例：至少7位数字)
	    if (!/^\d{7,}$/.test(this.scanInput)) {
	      this.$message.error('追溯码格式不正确，请输入至少7位数字');
	      return;
	    }
	    
	    // 提取追溯码前7位
	    this.traceCodePrefix = this.scanInput.substring(0, 7);
	    
	    // 在rightTableData中查找匹配的药品
	    this.findMatchingMedicines();
	},

	// 查找匹配的药品
	findMatchingMedicines() {
	    this.matchedMedicines = [];
	      
	    // 检查当前处方是否有药品数据
	    if (!this.rightTableData || this.rightTableData.length === 0) {
	      this.$message.warning('当前处方无药品信息');
	      return;
	    }
	      
	    // 遍历rightTableData查找匹配的药品
	    this.rightTableData.forEach(item => {
	      // 确保drugTracMaxId是字符串类型
	      const maxId = String(item.drugTracMaxId || '');
	          
	      // 检查追溯码前缀是否匹配
	      if (maxId === this.traceCodePrefix) {
	        this.matchedMedicines.push({
	          ...item, // 包含药品完整信息
	          traceId: this.traceCodePrefix,  // 追溯标识码
	          fullTraceCode: this.scanInput   // 完整追溯码
	        });
	      }
	    });
	      
	    if (this.matchedMedicines.length === 0) {
	      this.$message.error(`未找到匹配的药品信息，追溯码前缀: ${this.traceCodePrefix}`);
	    } else {
	      this.$message.success(`找到${this.matchedMedicines.length}个匹配的药品`);
		  console.log(this.matchedMedicines,'找到${this.matchedMedicines.length}个匹配的药品');
	    }
	},

	// 模拟扫码成功
	// simulateScanSuccess() {
	//   // 生成随机追溯码
	//   const randomCode = Math.floor(10000000 + Math.random() * 90000000).toString();
	//   this.scanInput = randomCode;
	//   this.handleScanInput();
	// },

	// 在扫码对话框中确认绑定追溯码
	async confirmTraceCode() {
	  if (!this.currentScanItem || this.matchedMedicines.length === 0) {
	    this.$message.warning('请先扫描有效的追溯码');
	    return;
	  }
	  
	  const scanInput = this.scanInput;
	  
	  // 更新匹配到的药品的追溯码信息
	  this.matchedMedicines.forEach(medicine => {
	    // 更新追溯码和数量
	    medicine.drgTracCode = scanInput;
	    medicine.drgTracCnt = medicine.drgTracCnt ? medicine.drgTracCnt + 1 : 1;
	    
	    // 标记为已采集
	    medicine.traceCodeCollected = true;
	    
	    // 更新追溯码表格数据
	    this.updateTraceCodeTableData(medicine);
	    
	    // 更新右侧表格数据
	    this.updateRightTableData(medicine);
	    
	    // 修复：确保更新 westernMedicines 中的对应项
	    const index = this.westernMedicines.findIndex(item => item.drugId === medicine.drugId);
	    if (index !== -1) {
	      // 使用 Vue.set 确保响应性
	      this.$set(this.westernMedicines, index, {
	        ...this.westernMedicines[index],
	        drgTracCode: scanInput,
	        drgTracCnt: medicine.drgTracCnt,
	        traceCodeCollected: true
	      });
	    }
	  });
	  
	  this.$message.success('追溯码绑定成功');
	  this.scanDialogVisible = false;
	  
	  // 更新发药对话框中的追溯码数量
	  this.sendMedicineData.traceCodeCount = this.calculateTraceCodeCount();
	},
	
	// 更新追溯码表格数据
	  updateTraceCodeTableData(medicine) {
	    const index = this.traceCodeTableData.findIndex(
	      item => item.rawData && item.rawData.drugId === medicine.drugId
	    );
	    
	    if (index !== -1) {
	      const updatedItem = {
	        ...this.traceCodeTableData[index],
	        drgTracCode: medicine.drgTracCode,
	        drgTracCnt: medicine.drgTracCnt,
	        sendStatus: '已关联'
	      };
	      
	      this.$set(this.traceCodeTableData, index, updatedItem);
	    }
	  },
	  
	  // 更新右侧表格数据
	updateRightTableData(medicine) {
	  const index = this.rightTableData.findIndex(
		item => item.drugId === medicine.drugId
	  );
	  
	  if (index !== -1) {
		this.$set(this.rightTableData, index, {...medicine});
	  }
	},
		
	// 计算追溯码采集完成状态 - 修复逻辑
	// isTraceCodeComplete() {
	//   return this.traceCodeTableData.every(item => {
	//     // 只需要检查强制追溯码药品
	//     if (item.rawData && item.rawData.drugTracB === 1) {
	//       return !!item.drgTracCode && item.drgTracCode.trim() !== '';
	//     }
	//     return true; // 非强制追溯码药品直接通过
	//   });
	// },

		
	// 更新药品状态
	updateMedicineStatus() {
	    // 检查是否所有强制追溯码药品都已采集
	    const allCollected = this.westernMedicines.every(item => 
	      item.drugTracB !== 1 || item.traceCodeCollected
	    );
	    
	    if (allCollected) {
	      this.$message.success('所有强制追溯码药品已完成采集');
	    }
	},
		
	// 确认发药
	async confirmSendMedicine() {
	  this.sendMedicineDialogVisible = false;
	  
	  // 检查是否有强制追溯码药品未采集
	  const hasUncollected = this.rightTableData.some(item => 
	    item.drugTracB === 1 && (!item.drgTracCode || item.drgTracCode === '')
	  );
	  
	  if (hasUncollected) {
	    this.$message.error('存在强制追溯码药品未采集，请先完成采集');
	    return;
	  }
	
	  // 清除之前的定时器
	  if (this.timer) {
	    clearTimeout(this.timer);
	  }
	
	  // 准备发药数据
	  const sendData = {
	    ...this.rightForm,
	    voList: this.rightTableData.map(item => ({
	      ...item,
	      drgTracCode: item.drgTracCode || '',
	      drgTracCnt: item.drgTracCnt || 0
	    }))
	  };
	console.log(sendData,'ooooooooooooooppppppppppppppp');
	  // 设置所有按钮为加载状态
	  this.setAllButtonsLoading(true);
	
	  try {
	    let res = await fySave(sendData);
	    
	    if (res.code === 200) {
	      this.$message({ type: 'success', message: res.message });
	      
	      // 如果需要同时打印
	      if (this.sendMedicineData.printTogether) {
	        await this.printReceipt();
	      }
	      
	      // 设置3秒后自动刷新
	      this.timer = setTimeout(() => {
	        this.reload();
	      }, 3000);
	      
	    } else {
	      this.$message.error(res.message);
	    }
	  } catch (error) {
	    console.error('发药出错:', error);
	    this.$message.error('发药失败');
	  } finally {
	    // 无论成功失败，都关闭加载状态
	    this.setAllButtonsLoading(false);
	  }
	},
	
	// 将药品数据转换为追溯码表格数据
	transformToTraceCodeData(medicineList) {
	    return medicineList.map(item => {
	      return {
	        medicineName: `${item.drugName} ${item.drugSpec}`,
	        productCode: item.prodentpName || '未知厂家',
	        sendStatus: '未关联',
	        sendCombo: `${item.cnt}${item.unt}`,
	        drgTracCnt: '0',
	        drgTracCode: '',
	        rawData: item // 保留原始数据以便后续操作
	      };
	    });
	},

	// 完成追溯码采集
	completeTraceCode() {
      // 检查是否所有强制追溯码药品都已采集
      const allCollected = this.traceCodeTableData.every(item => {
        // 只需要检查强制追溯码药品
        if (item.rawData && item.rawData.drugTracB === 1) {
          return !!item.drgTracCode && item.drgTracCode.trim() !== '';
        }
        return true; // 非强制追溯码药品直接通过
      });
      
      if (!allCollected) {
        this.$message.error('请先完成所有强制追溯码药品的采集');
        return;
      }
    
      // 更新rightTableData中的追溯码信息
      this.rightTableData = this.rightTableData.map(item => {
        const traceItem = this.traceCodeTableData.find(t => 
          t.rawData && t.rawData.drugId === item.drugId
        );
        if (traceItem) {
          return {
            ...item,
            drgTracCode: traceItem.drgTracCode,
            drgTracCnt: traceItem.drgTracCnt,
            traceCodeCollected: true // 确保设置采集状态
          };
        }
        return item;
      });
    
      // 更新发药对话框中的药品状态
      this.westernMedicines = this.westernMedicines.map(item => {
        const updatedItem = {...item};
        
        // 更新状态 - 强制追溯码药品
        if (item.drugTracB === 1) {
          // 检查是否已采集追溯码
          const traceItem = this.traceCodeTableData.find(t => 
            t.rawData && t.rawData.drugId === item.drugId
          );
          
          if (traceItem && traceItem.drgTracCode) {
            updatedItem.traceCodeCollected = true;
          }
        }
        
        return updatedItem;
      });
    
      // 强制更新视图
      this.$forceUpdate();
    
      this.traceCodeDialogVisible = false;
      this.$message.success('追溯码采集完成');
      
      // 重新打开发药对话框
      this.sendMedicineDialogVisible = true;
    },
	
	// 暂存追溯码
	// saveTemporary() {
	//   this.$message.info('追溯码已暂存');
	// },
	
	// 打印收据
	async printReceipt() {
	  try {
		// 调用打印接口
		await this.$print.executePrint();
		this.$message.success('打印成功');
	  } catch (error) {
		console.error('打印失败:', error);
		this.$message.error('打印失败');
	  }
	},
	
	// 关闭对话框处理
	handleSendMedicineClose(done) {
	  this.$confirm('确认取消发药？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	  }).then(() => {
		done();
		this.$message.info('已取消发药');
	  }).catch(() => {});
	},
	
	handleTraceCodeClose(done) {
	  this.$confirm('确认关闭追溯码采集？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	  }).then(() => {
		done();
		// 重新打开发药对话框
		this.sendMedicineDialogVisible = true;
	  }).catch(() => {});
	},
	setAllButtonsLoading(isLoading) {
	    this.loading = isLoading;
	    // 设置所有按钮的加载状态
	    for (let key in this.buttonLoading) {
	      this.buttonLoading[key] = isLoading;
	    }
	  },
	// 添加合计行计算方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        
        // 只对金额和数量列进行合计
        if (column.property === 'purcAmt' || column.property === 'cnt') {
          const values = data.map(item => {
            // 确保数据是数字类型
            const value = Number(item[column.property]);
            return isNaN(value) ? 0 : value;
          });
          
          // 计算合计值
          const sum = values.reduce((prev, curr) => prev + curr, 0);
          
          // 金额保留2位小数
          sums[index] = column.property === 'purcAmt' ? sum.toFixed(2) : sum;
        } else {
          sums[index] = '';
        }
      });
    
      return sums;
    },
    calculateTableHeights() {
      // 计算左侧表格高度
      const leftFormHeight = document.querySelector('.left-form')?.offsetHeight || 300;
      const leftTableHeight = window.innerHeight - 50 - 50 - leftFormHeight - 20; // 减去header、bottom和form高度以及padding
      this.leftTableHeight = Math.max(200, leftTableHeight) + 'px';
      
      // 计算右侧表格高度
      const rightFormHeight = document.querySelector('.right-form')?.offsetHeight || 300;
      const rightTableHeight = window.innerHeight - 50 - 50 - rightFormHeight - 20; // 减去header、bottom和form高度以及padding
      this.rightTableHeight = Math.max(200, rightTableHeight) + 'px';
    }
  }
}
</script>

<style lang="less" scoped>
	/* 添加合计行样式 */
	/deep/ .el-table__footer-wrapper .el-table__footer .cell {
	  font-weight: bold;
	  color: #aa0000;
	}
/* 完成发药对话框样式 */
.send-medicine-dialog /deep/ .el-dialog__header {
  border-bottom: 1px solid #e8e8e8;
  padding: 16px 20px;
}

/deep/ .el-link{
	justify-content:left;
}
.send-medicine-dialog /deep/ .el-dialog__body {
  padding: 20px;
}

.send-medicine-content {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
  .medicine-list {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease;
    
    &.expanded {
      max-height: 500px; /* 根据实际内容高度调整 */
    }
  }
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.value {
  flex: 1;
  color: #303133;
}

.medicine-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.trace-code-link {
  font-size: 14px;
}

.medicine-type {
  color: #606266;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.footer-buttons {
  display: flex;
  gap: 12px;
}

/* 追溯码采集对话框样式 */
.trace-code-dialog /deep/ .el-dialog__body {
  padding: 20px;
}

.important-reminder {
  background: #fff6e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 16px;
}

.reminder-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #d46b08;
  font-weight: 500;
}

.reminder-header i {
  margin-right: 8px;
}

.reminder-content p {
  margin: 4px 0;
  color: #d46b08;
  font-size: 13px;
  line-height: 1.5;
}

.scan-input-area {
  margin-bottom: 16px;
}

.trace-code-input {
  margin-bottom: 8px;
}

.input-tips {
  display: flex;
  gap: 16px;
  font-size: 13px;
}

.trace-code-table /deep/ .el-table__cell {
  padding: 8px 0;
}

.no-trace-code {
  color: #909399;
  font-style: italic;
}

.trace-code-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.send-medici-container {
  width: 100%;
  height: 90vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  overflow: hidden;
  
  .send-medici-header {
    height: 50px;
    background-color: #409EFF;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 20px;
    flex-shrink: 0;
    
    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: normal;
    }
  }
  
  .send-medici-main {
    flex: 1;
    display: flex;
    overflow: hidden;
    
    .send-medici-left {
      width: 20%;
      height: 100%;
      display: flex;
      flex-direction: column;
      border-right: 1px solid #e6e6e6;
      background-color: white;
      overflow: hidden;
      
      /* 新增样式 */
      .left-form {
        padding: 10px;
        border-bottom: 1px solid #e6e6e6;
        overflow-y: auto;
        flex-shrink: 0;
        
        .el-form-item {
          margin-bottom: 10px;
          
          .form-item-row {
            display: flex;
            align-items: left;
            width: 100%;
            
            .form-label {
              width: 58px;
              text-align: left;
              padding-right: 10px;
              color: #606266;
            }
            
            .el-select, .el-input {
              flex: 1;
              min-width: 88px;
            }
            
          }
        }
      }
      
      .left-table {
        flex: 1;
        overflow: auto;
        padding: 10px;
      }
    }
    
    .send-medici-right {
      width: 80%;
      height: 100%;
      display: flex;
      flex-direction: column;
      background-color: white;
      overflow: hidden;
      
      .right-form {
        padding: 10px;
        border-bottom: 1px solid #e6e6e6;
        overflow-y: auto;
        flex-shrink: 0;
        
        .el-form-item {
          margin-bottom: 10px;
          width: 100%;
        }
        
        .el-row {
          margin-bottom: 10px;
        }
      }
      
      .right-table {
        flex: 1;
        overflow: auto;
        padding: 10px;
      }
    }
  }
  
  .send-medici-bottom {
    height: 50px;
    background-color: white;
    border-top: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    flex-shrink: 0;
    
    .bottom-left, .bottom-right {
      display: flex;
      align-items: center;
    }
  }
}
</style>